import axios, { AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { MessagePlugin } from 'tdesign-vue-next'
import { useUserStore } from '@/store'
import router from '@/router'
import { globalState } from '@/utils/globalState'

const request = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 1000,
    headers: {
        'Content-Type': 'application/json',
    },
});

request.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const token = useUserStore().token;
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    }
);

request.interceptors.response.use(
    (response: AxiosResponse) => {
        return response.data;
    },
    (error: any) => {
        let errorMessage = '';
        if (error.response && error.response.status == 401) {
            // token 过期或者无效
            errorMessage = error.response.data.message;
            MessagePlugin.error(errorMessage, 1000);
            const userStore = useUserStore();
            userStore.clearUserInfo();
            router.push({
                path: '/login',
            });
        }
        else if (error.response && error.response.status == 403) {
            if (!globalState.is403MessageShowing) {
                globalState.is403MessageShowing = true;
                errorMessage = error.response.data.message || '无访问权限';
                MessagePlugin.error(errorMessage, 1000);

                // 3秒后重置状态
                setTimeout(() => {
                    globalState.is403MessageShowing = false;
                }, 3000);
            }
        }
        else {
            errorMessage = error.response.data.message ? error.response.data.message : '网络错误，请稍后重试';
            MessagePlugin.error(errorMessage);
        }
        return Promise.reject(error);
    }
);

export default request;
